package com.findyou.headline.controller;

import com.findyou.headline.common.Result;
import com.findyou.headline.pojo.NewsHeadline;
import com.findyou.headline.service.NewsHeadlineService;
import com.findyou.headline.service.impl.NewsHeadlineServiceImpl;
import com.findyou.headline.util.JwtHelper;
import com.findyou.headline.util.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/headline/*")
public class NewsHeadlineController extends BaseController{
    private NewsHeadlineService newsHeadlineService = new NewsHeadlineServiceImpl();
    /**
     *发布头条的接口实现
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void publish(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收参数的过程
        String token = req.getHeader("token");
        Long userId = JwtHelper.getUserId(token);

        NewsHeadline newsHeadline = WebUtil.readJson(req, NewsHeadline.class);
        newsHeadline.setPublisher(userId.intValue());

        //将信息 存入数据库
        newsHeadlineService.addNewsHeadline(newsHeadline);

        //
        WebUtil.writeJson(resp, Result.ok(null));

    }

    /**
     * 根据hid 返回新闻的完整信息 响应给前端
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void findHeadlineByHid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int hid = Integer.parseInt(req.getParameter("hid")); // 拿到hid
//        NewsHeadline headline = newsHeadlineService.findByHid(hid);
        Map headline = new HashMap();
        headline.put("headline", newsHeadlineService.findByHid(hid));
        WebUtil.writeJson(resp, Result.ok(headline));
    }

    /**
     * 更新操作业务接口的实现
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        NewsHeadline newsHeadline = WebUtil.readJson(req, NewsHeadline.class);
        newsHeadlineService.update(newsHeadline);
        WebUtil.writeJson(resp, Result.ok(null));
    }

    /**
     * 将要删除的id发给服务端  这个是进行删除的 其实是修改业务接口的实现
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void removeByHid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int hid = Integer.parseInt(req.getParameter("hid"));
        newsHeadlineService.removeByHid(hid);

        WebUtil.writeJson(resp, Result.ok(null));
    }
}
